
package node;

import java.io.IOException;
import java.rmi.AccessException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import message.Message;
import message.MessageType;

/**
 * The ability to store data in a ring.
 * 
 * @author TCSS 558 Team 6
 * @version Spring 2013
 * 
 */
public class NodePut
{

  /**
   * The node.
   */
  private static Node my_node;
  /**
   * 
   * @param the_registry .
   * @throws AccessException
   * @throws RemoteException
   */

  public static void isSettled(final Registry the_registry) throws AccessException,
      RemoteException
  {
    final String[] registered_nodes = the_registry.list();
    if (registered_nodes.length != 0)
    {
      System.out.println("The system is ready");
    }
  }

  /**
   * @param the_args .
   */
  public static void main(String[] the_args)
  {

    int test_node_id = Integer.parseInt(the_args[5]);
   

    // get a reference to the remote registry.
    final String host = the_args[0];
    final int port = Integer.parseInt(the_args[1]);
    final String registry_name = the_args[2];
    final String key = the_args[3];
    final String value = the_args[4];
    try
    {
      final Registry bootstrap = LocateRegistry.getRegistry(host, port);
      final Registry registry = (Registry) bootstrap.lookup(registry_name);
      // checks if the system is set up.
      isSettled(registry);

     
      my_node = (Node) registry.lookup("node_id_" + test_node_id);

     

      int nodeid = my_node.getMyID();
      System.out.println("node id being tested: " + nodeid);

      // hashes the key and gets the the destination;
      int hash = key.hashCode();
      if (hash < 0)
      {
        hash *= -1;
      }
      int destination = hash % (1 << 3);
      System.out.println("the hashed node id this key will go to: " + destination);

      

      Message response = (Message) ((Node) my_node).put(key, value);

      System.out.println("this came back from the network: " + response.getValue());

    }
    catch (IOException e)
    {
      
      e.printStackTrace();
    }
    catch (NotBoundException e)
    {
     
      e.printStackTrace();
    }
  }

}
